package handlers

import (
	"data_service/server"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 初始化好友业务服务
var friendService = server.NewFriendService()

// AddFriendHandler 添加好友
func AddFriendHandler(c *gin.Context) {
	var req struct {
		UserID   int `json:"user_id" binding:"required"`
		FriendID int `json:"friend_id" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}
	if err := friendService.AddFriend(req.UserID, req.FriendID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "添加好友失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "添加好友成功"})
}

// GetFriendsHandler 获取好友列表
func GetFriendsHandler(c *gin.Context) {
	userIDStr := c.Query("user_id")
	userID, _ := strconv.Atoi(userIDStr)
	friends, err := friendService.GetFriends(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取好友失败"})
		return
	}
	c.JSON(http.StatusOK, friends)
}

// DeleteFriendHandler 删除好友
func DeleteFriendHandler(c *gin.Context) {
	var req struct {
		UserID   int `json:"user_id" binding:"required"`
		FriendID int `json:"friend_id" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}
	if err := friendService.DeleteFriend(req.UserID, req.FriendID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除好友失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "删除好友成功"})
}
